import re
from collections import defaultdict
import datetime

# 定义正则表达式来匹配各个输出文件的行
open_re = re.compile(r'(\d+\.\d+)\s+(\S+)\s+\d+\s+\d+\s+\S+\s+\d+')
write_re = re.compile(r'(\d+\.\d+)\s+(\S+)\s+\d+\s+\d+\s+\S+\s+\d+')
sync_re = re.compile(r'(\d+\.\d+)\s+(\S+)\s+\d+\s+\d+\s+\S+\s+\d+')
bio_re = re.compile(r'(\d+\.\d+)\s+(\S+)\s+\d+\s+[RW]\s+\S+\s+\d+\s+\d+\s+\d+\.\d+')

# 用于存储数据的字典
event_counter = defaultdict(lambda: defaultdict(int))
timestamps = defaultdict(list)

# 读取并处理 opensnoop 输出文件
with open('opensnoop_output.txt', 'r') as f:
    for line in f:
        match = open_re.match(line)
        if match:
            timestamp, process_name = match.groups()
            event_counter['open'][process_name] += 1
            timestamps['open'].append(float(timestamp))

# 读取并处理 writesnoop 输出文件
with open('writesnoop_output.txt', 'r') as f:
    for line in f:
        match = write_re.match(line)
        if match:
            timestamp, process_name = match.groups()
            event_counter['write'][process_name] += 1
            timestamps['write'].append(float(timestamp))

# 读取并处理 syncsnoop 输出文件
with open('syncsnoop_output.txt', 'r') as f:
    for line in f:
        match = sync_re.match(line)
        if match:
            timestamp, process_name = match.groups()
            event_counter['sync'][process_name] += 1
            timestamps['sync'].append(float(timestamp))

# 读取并处理 biosnoop 输出文件
with open('biosnoop_output.txt', 'r') as f:
    for line in f:
        match = bio_re.match(line)
        if match:
            timestamp, process_name = match.groups()
            event_counter['bio'][process_name] += 1
            timestamps['bio'].append(float(timestamp))

# 打印统计结果
print("事件统计:")
for event_type, processes in event_counter.items():
    print(f"{event_type} 事件统计:")
    for process_name, count in processes.items():
        print(f"  {process_name}: {count} 次")

# 计算和打印时间间隔
print("\n事件时间间隔统计:")
for event_type, times in timestamps.items():
    if len(times) > 1:
        intervals = [t1 - t0 for t0, t1 in zip(times, times[1:])]
        avg_interval = sum(intervals) / len(intervals)
        print(f"{event_type} 平均时间间隔: {avg_interval:.4f} 秒")